/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.worldscale.xp.wslib.im.jabber.impl;

import net.worldscale.xp.wslib.im.jabber.JabberClient;
import net.worldscale.xp.wslib.im.jabber.JabberMessageList;
import net.worldscale.xp.wslib.im.jabber.JabberRosterModel;

/**
 *
 * @author Kun
 */
final class UserSession {

    private final ClientSession mParentSession;
    private WorkSession mCurWork;
    private boolean mIsClosed = false;
    private int mMsLaterRetry = 0;
    private final JabberClient.LoginContext mLC;
    private final JabberRosterModel mRosterModel;
    private final JabberMessageList mMessageList;

    public UserSession(ClientSession parent, JabberClient.LoginContext lc) {
        mParentSession = parent;
        mLC = lc;
        mRosterModel = new ImplRosterModel();
        mMessageList = new ImplMessageList(lc.getJID());
    }

    public JabberRosterModel getRosterModel() {
        return this.mRosterModel;
    }

    public JabberMessageList getMessageList() {
        return mMessageList;
    }

    public void proc() {
        System.out.println(this + ".proc - begin");
        try {
            for (; !this.mIsClosed;) {
                final WorkSession ws = new WorkSession(this);
                this.mCurWork = ws;
                ws.proc();
                this.mCurWork = null;
                // 稍后重登录
                mMsLaterRetry = 5000;
                final int step = 500;
                while ((mMsLaterRetry > 0) && (!this.mIsClosed)) {
                    mMsLaterRetry -= step;
                    Thread.sleep(step);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(this + ".proc - end");
    }

    public void close() {
        this.mIsClosed = true;
    }

    public WorkSession getCurWork() {
        return mCurWork;
    }

    public JabberClient.LoginContext getLoginContext() {
        return mLC;
    }

    public ClientSession getParentSession() {
        return mParentSession;
    }

    public int getPhase() {
        final WorkSession ws = this.mCurWork;
        if (ws == null) {
            return JabberClient.PHASE_OFFLINE;
        } else {
            return ws.getPhase();
        }
    }
}
